﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CodeGenerator.Common;
using System.Xml;
using System.IO;

namespace CodeGenerator.Core
{
    public class Config
    {
        #region 链接服务器
        /// <summary>
        /// 得到连接字符串
        /// </summary>
        /// <param name="serverID"></param>
        /// <returns></returns>
        public static string GetConnectionString(ServerInfo server, string dbName = "")
        {

            if (server == null)
            {
                return string.Empty;
            }
            else
            {
                string connString = string.Empty;
                switch (server.DBType)
                {
                    case DatabaseType.SqlServer:
                        connString = string.Format(server.ConnectString + ";Initial Catalog={0};", dbName.IsNullOrEmpty() ? Constant.DatabaseName : dbName);
                        break;
                    case DatabaseType.MySql:
                        connString = string.Format(server.ConnectString + ";Initial Catalog={0};", dbName.IsNullOrEmpty() ? Constant.DatabaseName : dbName);
                        break;
                    case DatabaseType.PostgreSQL:
                        connString = string.Format(server.ConnectString + ";Database={0};", dbName.IsNullOrEmpty() ? Constant.DatabaseName : dbName);
                        break;
                    default:
                        connString = server.ConnectString;
                        break;
                }

                return connString;
            }
        }

        /// <summary>
        /// 得到连接字符串
        /// </summary>
        /// <param name="serverID"></param>
        /// <returns></returns>
        public static string CreateConnectionString(ServerInfo server, string userName, string pwd)
        {

            if (server == null)
            {
                return string.Empty;
            }
            else
            {
                string connString = string.Empty;
                switch (server.DBType)
                {
                    case DatabaseType.SqlServer:
                        connString = string.Format("Data Source={0};Persist Security Info=True;User ID={1};Password={2}", server.ServerName, userName, pwd);
                        break;
                    case DatabaseType.Oracle:
                        connString = string.Format("password={0};User ID={1};Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={2})(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME={3})))",
                            pwd.IsNullOrEmpty() ? "" : string.Format("Password={0}", pwd), userName, server.ServerName, server.DatabaseName);
                        break;
                    case DatabaseType.MySql:
                        // Data Source=localhost;port=3306;Initial Catalog=kskf_icon;user id=root;password=123456
                        connString = string.Format("Data Source={0};Uid={1};Pwd={2};Charset=utf8", server.ServerName, userName, pwd);
                        break;
                    case DatabaseType.Sqlite:
                        connString = string.Format("Data Source={0};Pooling=true;FailIfMissing=false;{1}", server.ServerName, pwd.IsNullOrEmpty() ? "" : string.Format("Password={0}", pwd));
                        break;
                    case DatabaseType.PostgreSQL:
                        // Data Source=localhost;port=3306;Initial Catalog=kskf_icon;user id=root;password=123456
                        connString = string.Format("Server={0};UserId={1};Password={2}", server.ServerName, userName, pwd);
                        break;
                }

                return connString;
            }
        }

        /// <summary>
        /// 获取服务器列表
        /// </summary>
        /// <returns></returns>
        public static List<ServerInfo> GetServerList()
        {
            List<ServerInfo> list = new List<ServerInfo>();
            XmlDocument objXmlDoc = new XmlDocument();
            string path = Path.Combine(Utils.GetAppPath(), @"Config\DatabaseSetting.xml");

            try
            {
                objXmlDoc.Load(path);
                XmlNodeList xmList = objXmlDoc.SelectNodes("DatabaseInfo/DatabaseSetting");
                foreach (XmlNode xn in xmList)
                {
                    ServerInfo entity = new ServerInfo();
                    entity.Alias = xn.SelectSingleNode("Alias").InnerText;
                    entity.DatabaseType = xn.SelectSingleNode("DatabaseType").InnerText;
                    entity.ServerName = xn.SelectSingleNode("ServerName").InnerText;
                    entity.ConnectString = xn.SelectSingleNode("ConnectString").InnerText;
                    entity.DatabaseName = xn.SelectSingleNode("DatabaseName").InnerText;

                    list.Add(entity);
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("加载服务器列表出错", ex);
            }
            return list;
        }

        /// <summary>
        /// 注销服务器
        /// </summary>
        /// <param name="server"></param>
        /// <returns></returns>
        public static bool RemovetServer(ServerInfo server)
        {
            bool result = false;
            XmlDocument objXmlDoc = new XmlDocument();
            string path = Path.Combine(Utils.GetAppPath(), @"Config\DatabaseSetting.xml");
            objXmlDoc.Load(path);
            List<ServerInfo> ConfigServerList = new List<ServerInfo>();
            XmlNodeList xmList = objXmlDoc.SelectNodes("DatabaseInfo/DatabaseSetting");
            try
            {

                foreach (XmlNode xn in xmList)
                {
                    if (xn.SelectSingleNode("ConnectString").InnerText == server.ConnectString)
                    {
                        XmlNode xmParent = xn.SelectSingleNode("ConnectString").ParentNode;
                        xmParent.ParentNode.RemoveChild(xmParent);
                        break;
                    }
                }
                objXmlDoc.Save(path);
                result = true;
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("注销服务器出错：", ex);
            }
            return result;
        }

        /// <summary>
        /// 添加数据库配置信息
        /// </summary>
        /// <param name="server">配置信息</param>
        /// <returns></returns>
        public static bool AddServer(ServerInfo server)
        {
            bool result = false;
            XmlDocument objXmlDoc = new XmlDocument();
            string path = Path.Combine(Utils.GetAppPath(), @"Config\DatabaseSetting.xml");
            objXmlDoc.Load(path);
            List<ServerInfo> list = new List<ServerInfo>();
            XmlNode root = objXmlDoc.SelectSingleNode("DatabaseInfo");
            try
            {
                //创建一个<DatabaseSetting>节点   
                XmlElement xe1 = objXmlDoc.CreateElement("DatabaseSetting");

                XmlElement xeAlias = objXmlDoc.CreateElement("Alias");
                xeAlias.InnerText = server.Alias;
                xe1.AppendChild(xeAlias);
                XmlElement xeDatabaseType = objXmlDoc.CreateElement("DatabaseType");
                xeDatabaseType.InnerText = server.DatabaseType;
                xe1.AppendChild(xeDatabaseType);
                XmlElement xeServerName = objXmlDoc.CreateElement("ServerName");
                xeServerName.InnerText = server.ServerName;
                xe1.AppendChild(xeServerName);
                XmlElement xeConnectString = objXmlDoc.CreateElement("ConnectString");
                xeConnectString.InnerText = server.ConnectString;
                xe1.AppendChild(xeConnectString);
                XmlElement xeDatabaseName = objXmlDoc.CreateElement("DatabaseName");
                xeDatabaseName.InnerText = server.DatabaseName;
                xe1.AppendChild(xeDatabaseName);


                root.AppendChild(xe1);

                objXmlDoc.Save(path);
                result = true;
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("配置服务器出错：", ex);
            }
            return result;
        } 
        #endregion

        #region 命名空间
        /// <summary>
        /// 添加配置信息
        /// </summary>
        /// <param name="server">配置信息</param>
        /// <returns></returns>
        public static bool EditSetupInfo(MainSetting entity)
        {
            bool result = false;
            XmlDocument objXmlDoc = new XmlDocument();
            string path = Path.Combine(Utils.GetAppPath(), @"Config\OtherSetting.xml");
            objXmlDoc.Load(path);
            List<Config> ConfigServerList = new List<Config>();
            XmlNode root = objXmlDoc.SelectSingleNode("Setting");
            try
            {
                root.RemoveAll();

                XmlElement xesub1 = objXmlDoc.CreateElement("NameSpace");
                xesub1.InnerText = entity.NameSpace;
                root.AppendChild(xesub1);

                XmlElement xesub2 = objXmlDoc.CreateElement("AreaName");
                xesub2.InnerText = entity.AreaName;
                root.AppendChild(xesub2);

                XmlElement xesub3 = objXmlDoc.CreateElement("OutputDir");
                xesub3.InnerText = entity.OutputDir;
                root.AppendChild(xesub3);

                XmlElement xesub4 = objXmlDoc.CreateElement("Prefix");
                xesub4.InnerText = entity.Prefix;
                root.AppendChild(xesub4);

                XmlElement xesub5 = objXmlDoc.CreateElement("EntityPackage");
                xesub5.InnerText = entity.EntityPackage;
                root.AppendChild(xesub5);

                XmlElement xesub6 = objXmlDoc.CreateElement("DaoPackage");
                xesub6.InnerText = entity.DaoPackage;
                root.AppendChild(xesub6);

                XmlElement xesub7 = objXmlDoc.CreateElement("Mapping");
                xesub7.InnerText = entity.Mapping;
                root.AppendChild(xesub7);

                XmlElement xesub8 = objXmlDoc.CreateElement("IServicePackage");
                xesub8.InnerText = entity.IServicePackage;
                root.AppendChild(xesub8);

                XmlElement xesub9 = objXmlDoc.CreateElement("ServicePackage");
                xesub9.InnerText = entity.ServicePackage;
                root.AppendChild(xesub9);
                
                objXmlDoc.Save(path);
                result = true;
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("编辑配置信息出错：", ex);
            }
            return result;
        }

        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <returns></returns>
        public static MainSetting GetSetupInfo()
        {
            MainSetting entity = new MainSetting();
            XmlDocument objXmlDoc = new XmlDocument();
            string path = Path.Combine(Utils.GetAppPath(), @"Config\OtherSetting.xml");

            try
            {
                objXmlDoc.Load(path);
                XmlNode xn = objXmlDoc.SelectSingleNode("Setting");

                entity.NameSpace = xn.SelectSingleNode("NameSpace").InnerText;
                entity.AreaName = xn.SelectSingleNode("AreaName").InnerText;
                entity.OutputDir = xn.SelectSingleNode("OutputDir").InnerText;
                entity.Prefix = xn.SelectSingleNode("Prefix").InnerText;

                entity.EntityPackage = xn.SelectSingleNode("EntityPackage").InnerText;
                entity.DaoPackage = xn.SelectSingleNode("DaoPackage").InnerText;
                entity.Mapping = xn.SelectSingleNode("Mapping").InnerText;
                entity.IServicePackage = xn.SelectSingleNode("IServicePackage").InnerText;
                entity.ServicePackage = xn.SelectSingleNode("ServicePackage").InnerText;
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("加载配置信息出错", ex);
            }

            return entity;
        }
        #endregion
    }
}
